package com.umbacos.udm.client.model;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.ui.HTML;
import com.umbacos.udm.client.arch.Popup;

public class AsyncComm {

	public static final String STAT = "cgi-bin/udm-stat.cgi";
	public static final String COMM = "cgi-bin/udm-cmd.cgi";
	public static final String DOWN = "cgi-bin/udm-down.cgi";
	public static final String META = "cgi-bin/udm-benc.cgi";
	public static final String UPLF = "cgi-bin/udm-2388.cgi";
	public static final String TRAN = "cgi-bin/udm-trans.cgi";

	public static final HTML SERVER_ERROR = new HTML("An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.");
		
	public String postData = "";
	public String getData = "";
	
	public static String getBaseUrl() { 
		String server=GWT.getModuleBaseURL();
		int slash=server.indexOf('/', 9) +1; // skip "http://" and include trailing "/"
		return server.substring(0, slash) + "udm/"; 
		}
	
	public void send(String cmd, RequestCallback rq){
		String url = getBaseUrl() + cmd + getData;
		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
		builder.setTimeoutMillis(10000);
		builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
		try {  
			builder.sendRequest(postData, rq);
			} catch (Exception e) { 
				new Popup("ERROR:", new HTML(e.getMessage()), Popup.POPUP_CLOSE).showPopup();	
			}
	}
	
	public void getTracker(String filename, RequestCallback rq){
		String url = getBaseUrl() + "trk/" + filename;
		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
		builder.setTimeoutMillis(10000);
		builder.setHeader("Content-Type", "text/plain");
		try {  
			builder.sendRequest(postData, rq);
			} catch (Exception e) { 
				new Popup("ERROR:", new HTML(e.getMessage()), Popup.POPUP_CLOSE).showPopup();	
			}
	}
	
	public void addPostData(String key, String value) {
		if (postData.length() > 0) postData += "&";
		postData += key + "=" + URL.encode(value);
	}

	public void addGetData(String key, String value) {
		if (getData.length() > 0) getData += "&";
		if (getData.length() == 0) getData = "?";
		getData += key + "=" + URL.encode(value);
	}

	public native static JavaScriptObject JSON(String serialized) /*-{
      return eval('(' + serialized + ')');
    }-*/;
}
